package com.wisdom.benefit.jufa.my;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ansen.http.net.HTTPCaller;
import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.DownLoadManager.DownloadService;

import java.io.File;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
import io.github.lizhangqu.coreprogress.ProgressUIListener;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class VersionInformationActivity extends BaseActivity {
    private RelativeLayout backRl;
    private Button btn;
    private TextView tv;
    private ProgressDialog progressDialog;
    MyReceiver receiver = new MyReceiver();
    private String url;
    private String newVersion;
    private String mandatoryUpdate;

    @Override
    protected int getLayout() {
        return R.layout.acticity_version_information;
    }

    @Override
    protected void initViews() {
        appUpdate();
        //返回按钮
        backRl = findViewById(R.id.version_information_back);
        //版本号
        tv = findViewById(R.id.version_information_tv);
        try {
            tv.setText(getVersionName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //检查更新
        btn = findViewById(R.id.version_information_btn);
        setClick();
        //设置状态栏为蓝色
        YCAppBar.setStatusBarColor(VersionInformationActivity.this,
                ContextCompat.getColor(VersionInformationActivity.this,
                        R.color.blue));
        String a = getVersionName(this);
        tv.setText(a);

        regist();
        checkPermission();

    }

    /**
     * 设置监听
     *
     * @return
     */
    private void setClick() {
        //返回按钮
        backRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //检查更新
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nowVersion = getVersionName(VersionInformationActivity.this);
                int isUpdate = compareVersion(newVersion, nowVersion);
                if (isUpdate > 0) {
                    if (mandatoryUpdate.equals("1")) {
                        showMandatoryUpdaloadDialog(url);
                    } else {
                        showUpdaloadDialog(url);
                    }
                } else {
                    Toast.makeText(VersionInformationActivity.this, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    public void checkPermission() {
        boolean isGranted = true;
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (VersionInformationActivity.this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果没有写sd卡权限
                isGranted = false;
            }
            if (VersionInformationActivity.this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            Log.i("cbs", "isGranted == " + isGranted);
            if (!isGranted) {
                (VersionInformationActivity.this).requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        102);
            }
        }

    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    public static String getVersionName(Context ctx) {
        // 获取packagemanager的实例
        String version = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            //getPackageName()是你当前程序的包名
            PackageInfo packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0);
            version = packInfo.versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    private void showUpdaloadDialog(final String downloadUrl) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.ic_launcher). // 设置提示框的图标
                setMessage("发现新版本！请及时更新").// 设置要显示的信息
                setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //判断是否有存储权限
                PackageManager pm = getPackageManager();
                boolean permission = (PackageManager.PERMISSION_GRANTED ==
                        pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.wisdom.benefit.jufa"));
                if (permission) {
                    startUpload(downloadUrl);
                } else {
                    Toast.makeText(VersionInformationActivity.this, "请您开启存储权限", Toast.LENGTH_SHORT).show();
                }
            }
        }).setNegativeButton("取消", null);//设置取消按钮,null是什么都不做，并关闭对话框
        AlertDialog alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
    }

    private void showMandatoryUpdaloadDialog(final String downloadUrl) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.ic_launcher). // 设置提示框的图标
                setMessage("发现新版本！请更新").// 设置要显示的信息
                setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //判断是否有存储权限
                PackageManager pm = getPackageManager();
                boolean permission = (PackageManager.PERMISSION_GRANTED ==
                        pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.wisdom.benefit.jufa"));
                if (permission) {
                    startUpload(downloadUrl);
                } else {
                    Toast.makeText(VersionInformationActivity.this, "请您开启存储权限", Toast.LENGTH_SHORT).show();
                }
            }
        });//设置取消按钮,null是什么都不做，并关闭对话框
        AlertDialog alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
        alertDialog.setCancelable(false);
    }

    /**
     * Activity中注册BroadcastReceiver，监听广播，更新UI
     */
    private void regist() {
        IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra(DownloadService.EXTENDED_DATA_STATUS);
            Log.i("test", data);

            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            Toast.makeText(VersionInformationActivity.this, "编号：" + id + "的下载任务已经完成！", Toast.LENGTH_SHORT).show();
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myApp.apk")),
                    "application/vnd.android.package-archive");
            startActivity(intent);

        }
    }

    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }


    /**
     * APP更新接口
     */
    private void appUpdate() {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .appUpdate()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        url = response.getData().getDownloadPath();
                        newVersion = response.getData().getVersionNumber();
                        mandatoryUpdate = response.getData().getMandatoryUpdate();
                    } else {

                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("获取更新数据失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    private void startUpload(String downloadUrl) {

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("正在下载新版本。。。");
        progressDialog.setCancelable(false);//不能手动取消下载进度对话框

        final String fileSavePath = getSaveFilePath(downloadUrl);
        HTTPCaller.getInstance().downloadFile(downloadUrl, fileSavePath, null, new ProgressUIListener() {

            //下载开始
            @Override
            public void onUIProgressStart(long totalBytes) {
                progressDialog.setMax((int) totalBytes);
                progressDialog.show();
            }

            //更新进度
            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                progressDialog.setProgress((int) numBytes);
            }

            //下载完成
            @Override
            public void onUIProgressFinish() {
                Toast.makeText(VersionInformationActivity.this, "下载完成", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                openAPK(fileSavePath);
            }

        });
    }

    public static String getSaveFilePath(String fileUrl) {
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());//获取文件名称
        String newFilePath = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
        return newFilePath;
    }

    private void openAPK(String fileSavePath) {

        File file = new File(fileSavePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // "cn.com.eyes3d.fileprovider"即是在清单文件中配置的authorities
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(this, "com.wisdom.benefit.jufa.fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
//            data = Uri.fromFile(file);
            data = FileProvider.getUriForFile(this, "com.wisdom.benefit.jufa.fileProvider", file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后提示：完成 打开
        startActivity(intent);

    }

    public static int compareVersion(String s1, String s2) {
        String[] s1Split = s1.split("\\.", -1);
        String[] s2Split = s2.split("\\.", -1);
        int len1 = s1Split.length;
        int len2 = s2Split.length;
        int lim = Math.min(len1, len2);
        int i = 0;
        while (i < lim) {
            int c1 = "".equals(s1Split[i]) ? 0 : Integer.parseInt(s1Split[i]);
            int c2 = "".equals(s2Split[i]) ? 0 : Integer.parseInt(s2Split[i]);
            if (c1 != c2) {
                return c1 - c2;
            }
            i++;
        }
        return len1 - len2;
    }

}
